<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-4-30
 * Time: 下午4:46
 */
//错误代码：
//INVENTORY_NOT_ENOUGH 库存不足
//PRICE_NOT_MATCH 价格不匹配
//CREATE_TRADE_FAILURE 订单创建失败
//OUT_SYSTEM_ERROR 系统异常
//PARAM_ILLEGAL 参数不合法
define('ALIPAY_ROOT', '/var/www/html/alipay/');
require_once(ALIPAY_ROOT . "alipay.config.php");
require_once(ALIPAY_ROOT . "lib/alipay_core.function.php");
require_once(ALIPAY_ROOT . "lib/alipay_md5.function.php");

include '../../common/func.inc.php';

//require_once(ALIPAY_ROOT . "lib/alipay_notify.class.php");
$data = file_get_contents('php://input');
write_logs($data, 'log.txt');
$str_get = json_encode($_GET);
write_logs($str_get, 'log.txt');
//签名验证
//if ( !verifyNotify() ) {
//    Response('F', 'PARAM_ILLEGAL');
//}

include '../../class/SoapInit.class.php';

$dbConf = include '../common/db.conf.php';
include '../common/Db.class.php';
$soap = new SoapClient(null,array(
        "location" => "http://localhost/open/openService/pft_insideMX.php",
        "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true")
);
//这里处理下单
$member = 4;//下单人ID
list($aid, $lid, $tid, $salerid) = explode('|', $_REQUEST['goods_id']);

//库存判断
$sql = "SELECT storage,storage_open FROM uu_jq_ticket WHERE id=? LIMIT 1";
\PFT\Db::Conf($dbConf['localhost']);
$stmt = \PFT\Db::Connect()->prepare($sql);
$stmt->execute(array($tid));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
write_logs($str_get, 'log.txt');

//if($row['storage']!=-1){//总库存
//    $storageXml=$soap->Dynamic_Storage_Check($row['tid'],2,NULL,$row['storage_open']);
//    $storageXml=simplexml_load_string($storageXml);
//    $sales=$storageXml->Rec->UUXstr;
//    $remain=$row['storage']-$sales;
//    if($row['tnum']>$remain){
//        Response('F', 'INVENTORY_NOT_ENOUGH');
//    }
//}
//
//
//
//$pstorage=$soap->get_Dynamic_Price_Merge($row['pid'],substr($row['begintime'],0,10),1,"","",0,1);
//$pstorage=explode(",",$pstorage);
//$pstorage=$pstorage[1];
//if($pstorage!=-1){//日库存
//    $dayxml=$soap->Dynamic_Storage_Check($row['tid'],1,substr($row['begintime'],0,10));
//    $dayxml=simplexml_load_string($dayxml);
//    $dayxml=(string)$dayxml->Rec->UUXstr;
//    $dayxml=explode("|",$dayxml);
//    $remain=$pstorage-$dayxml[1];
//    if($row['tnum']>$remain){
//        throw new DisOrderException(substr($row['begintime'],0,10)." ".$row['ltitle'].$row['ttitle']."日库存数不足，剩余 $remain 张门票");
//    }
//}

//价格判断
//$soap->Dynamic_Price_And_Storage($ac, $pid, $date='', $mode=0,
//    $ptype=0, $get_storage=0, $m, $sdate='', $edate='');

$begintime = $endtime = date('Y-m-d', $_SERVER['REQUEST_TIME']);
$totalmoney = floatval($_REQUEST['price']) * 100;//用户购买商品的总价，单位元，精确到小数点后 2 位
$tnum = intval($_REQUEST['quantity']);
$tprice = $totalmoney / $tnum / 100;
write_logs('tprice='.$tprice, 'log.txt');
$contactTEL = '';
$ordertel   = isset($_REQUEST['phone']) ? safetxt($_REQUEST['phone']) :'';
$smsSend    = 1;//isset($_REQUEST['phone']) ? 0 : 1;//默认不发送短信
//远端订单号，买家支付宝账号+时间戳
$remotenum  = strval(substr($_REQUEST['user_id'],3).$_SERVER['REQUEST_TIME']);

$ordername  = '扫码下单用户';
$paymode = 1;//支付宝支付
$ordermode=0;//下单方式（0正常分销商下单，其他方式暂时屏蔽）
$series = '';
$assembly = 0;

write_logs("$member, $lid, $tid, $begintime,
                   $endtime, $tprice, $tnum, $totalmoney,
                   5, $ordertel, $contactTEL, $salerid,
                   $aid,$paymode, $ordermode, $remotenum,
                   $assembly, $series, $smsSend" , 'log.txt');

$ret = $soap->Group_Order_Submit($member, $lid, $tid, $begintime,
                   $endtime, $tprice, $tnum, $totalmoney,
                   5, $ordertel, $contactTEL, $salerid,
                   $aid,$paymode, $ordermode, $remotenum,
                   $assembly, $series, $smsSend);

if ($ret>100000) {
    Response('T', $ret);
} else {
    write_logs($ret, 'log.txt');
    Response('F', 'CREATE_TRADE_FAILURE');
}

function Response($status, $str) {
    $output = array('is_success'=>$status);
    if ($status=='F') {
        $output['error_code'] = $str;
    } else {
        $output['out_trade_no'] = $str;
    }
    echo json_encode($output);
    exit;
}
function getSignVeryfy($para_temp, $sign) {
    //除去待签名参数数组中的空值和签名参数
    $para_filter = paraFilter($para_temp);
    //对待签名参数数组排序
    $para_sort = argSort($para_filter);
    //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
    $prestr = createLinkstring($para_sort);
    $isSgin = false;
    switch (strtoupper(trim($this->alipay_config['sign_type']))) {
        case "MD5" :
            $isSgin = md5Verify($prestr, $sign, $this->alipay_config['key']);
            break;
        default :
            $isSgin = false;
    }
    return $isSgin;
}
function verifyNotify()
{
    if(empty($_REQUEST)) {//判断POST来的数组是否为空
        return false;
    }
    else {
        //生成签名结果
        $isSign = getSignVeryfy($_REQUEST, $_REQUEST["sign"]);
        //获取支付宝远程服务器ATN结果（验证是否是支付宝发来的消息）
        $responseTxt = 'true';
        //验证
        //$responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
        //isSign的结果不是true，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
        if (preg_match("/true$/i",$responseTxt) && $isSign) {
            return true;
        } else {
            return false;
        }
    }
}